package com.zhehekeji.opsys.api.service.manager;

import org.apache.cxf.common.util.StringUtils;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.zhehekeji.opsys.api.common.util.ResultCode;
import com.zhehekeji.opsys.api.dao.MongoDaoImpl;
import com.zhehekeji.opsys.api.enm.MongoCollectionName;
import com.zhehekeji.opsys.api.resp.StatisticalTrafficResp;

/**
 * @ClassName MongoDataSatisticsService
 * @Description TODO
 * @author chenweiliu chenwei.liu@163.com
 * @date 2015-5-29   下午3:01:25
 */
public class MongoDataSatisticsService implements IDataSatisticsService {
	
	private static Logger logger = LoggerFactory.getLogger(MongoDataSatisticsService.class);
	private MongoDaoImpl mongoDao;
	
	public void setMongoDao(MongoDaoImpl mongoDao) {
		this.mongoDao = mongoDao;
	}

	@Override
	public StatisticalTrafficResp statisticalTraffic(String productCode) {

		StatisticalTrafficResp resp = new StatisticalTrafficResp();
		if (StringUtils.isEmpty(productCode)){
			logger.error("统计产品访问量失败，产品编码非法！");
			resp.setResultCode(ResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc("统计产品访问量失败，产品编码非法！");
			return resp;
		}
		try {
			 MongoCollection<Document> tmpCollection = mongoDao.getCollection(MongoCollectionName.TVisitLog.getName());
			 long count = tmpCollection.count(Filters.eq("productCode", productCode));
			resp.setTraffic(count);
			logger.info("统计产品访问量成功");
		} catch (Exception e) {
			logger.error("统计产品访问量失败，系统异常，" + e.getMessage(), e);
			resp.setResultCode(ResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("统计产品访问量失败，系统异常");
		}
		return resp;
	}

}
